package com.dr.cmdb.gateway.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * @ProjectName: cmdb-gateway
 * @Package: com.dr.cmdb.gateway.config
 * @Description: java类作用描述
 * @Author: duanrui
 * @CreateDate: 2021/4/21 21:29
 * @Version: 1.0
 * <p>
 * Copyright: Copyright (c) 2021
 */
@Slf4j
@Configuration
public class AccessLogGlobalFilterConfig {

    private final ObjectMapper objectMapper = new ObjectMapper();
    @Bean
    @Order(0)
    public GlobalFilter accessLogGlobalFilter() {
        return (exchange, chain) -> {
            long startTime = System.currentTimeMillis();

            return chain.filter(exchange).doFinally((signalType) -> {
                long endTime = System.currentTimeMillis();

                ServerHttpRequest request = exchange.getRequest();
                try {
                    ObjectNode node = objectMapper.createObjectNode();
                    node.put("path", request.getPath().value());
                    node.put("queryParams", objectMapper.writeValueAsString(request.getQueryParams()));
                    node.put("remoteAddress", request.getRemoteAddress().getHostString());

                    HttpStatus httpStatus = exchange.getResponse().getStatusCode();
                    node.put("statusName", httpStatus.name());
                    node.put("statusValue", httpStatus.value());

                    node.put("elapsedMillisecond", endTime - startTime);
                    log.info(node.toString());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
        };
    }
}
